import os
import random
from moviepy import AudioFileClip, ImageClip, CompositeVideoClip
from utils.animation import create_animated_image_clip
from utils.subtitles import generate_srt_content
from config import config


def create_video_from_audio_image(
    audio_path: str,
    image_path: str,
    output_path: str,
    subtitle_text: str = None,
    animation_type: str = "pan",
) -> str:
    try:
        audio = AudioFileClip(audio_path)

        if animation_type == "random":
            animation_types = ["pan", "zoom"]
            animation_type = random.choice(animation_types)

        print(f"使用动画效果: {animation_type}")

        if animation_type == "static":
            image = ImageClip(image_path, duration=audio.duration)
            video_w, video_h = config.video.size
            video_aspect = video_w / video_h
            
            img_w, img_h = image.w, image.h
            img_aspect = img_w / img_h
            
            if img_aspect > video_aspect:
                image = image.resized(height=video_h)
            else:
                image = image.resized(width=video_w)
            
            image = image.resized((video_w, video_h))
        else:
            image = create_animated_image_clip(
                image_path, audio.duration, config.video.size, animation_type
            )

        print(f"图片加载成功，持续时间: {image.duration}秒，动画类型: {animation_type}")

        video_clips = [image]

        if subtitle_text:
            print(f"正在生成SRT字幕: {subtitle_text[:50]}...")
            
            srt_content = generate_srt_content(subtitle_text, audio.duration)
            
            srt_filename = output_path.replace(".mp4", ".srt")
            with open(srt_filename, "w", encoding="utf-8") as f:
                f.write(srt_content)
            print(f"SRT字幕文件已保存: {srt_filename}")

        final_video = CompositeVideoClip(video_clips, size=config.video.size)
        final_video = final_video.with_audio(audio)

        final_video.write_videofile(
            output_path, fps=config.video.segment_fps, audio_codec="aac", codec="libx264"
        )

        audio.close()
        image.close()
        final_video.close()

        return output_path

    except Exception as e:
        print(f"视频合成错误: {e}")
        raise